<template>
  <div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button size="small" type="primary" icon="plus" @click="addMenu()">新增根菜单</el-button>
      </div>

      <el-table :data="tableData" row-key="id">
        <!-- <el-table-column align="left" label="ID" min-width="100" prop="id" /> -->
        <el-table-column align="left" label="名称" show-overflow-tooltip min-width="160" prop="name" />
		<el-table-column align="left" label="图标" min-width="60" prop="icon">
		  <template #default="scope">
		    <div v-if="scope.row.icon" class="icon-column">
		      <el-icon>
		        <component :is="scope.row.icon" />
		      </el-icon>
		    </div>
		  </template>
		</el-table-column>
        <el-table-column align="left" label="路由" show-overflow-tooltip min-width="200" prop="path" />
        <el-table-column align="left" label="组件" show-overflow-tooltip min-width="200" prop="component" />
		<el-table-column align="left" label="类型" min-width="100" prop="type" >
		  <template #default="scope">
			<!-- <span v-if="scope.row.type === 'menu'">菜单</span>
			<span v-if="scope.row.type === 'button'">按钮</span> -->
			<!-- <span v-if="scope.row.type === 'function'">隐藏功能</span> -->
			<div v-for="item in typeOptions"><span v-if="item.value === scope.row.type">{{item.label}}</span></div>
		  </template>
		</el-table-column>
		<el-table-column align="left" label="排序" min-width="100" prop="sort" />
        <el-table-column align="left" label="是否隐藏" min-width="100" prop="hidden">
          <template #default="scope">
            <!-- <span>{{ scope.row.hidden === 1?"隐藏":"显示" }}</span> -->
			<div v-for="item in isnotOptions"><span v-if="item.value === scope.row.hidden">{{item.label}}</span></div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="备注" min-width="360" prop="remark" />
        <el-table-column align="left" fixed="right" label="操作" width="300">
          <template #default="scope">
            <el-button
              size="small"
              type="text"
              icon="plus"
              @click="addMenu(scope.row)"
            >添加子菜单</el-button>
			<el-button
			  icon="setting"
			  size="small"
			  type="text"
			  @click="opdendrawer(scope.row)"
			>关联资源</el-button>
            <el-button
              size="small"
              type="text"
              icon="edit"
              @click="editMenu(scope.row)"
            >编辑</el-button>
            <el-button
              size="small"
              type="text"
              icon="delete"
              @click="deleteMenuAction(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
	
    <el-dialog v-model="dialogFormVisible" :before-close="handleClose" :title="dialogTitle">
      <warning-bar title="新增菜单，需要在角色管理内配置权限才可使用" />
      <el-form
        v-if="dialogFormVisible"
        ref="menuForm"
        :inline="true"
        :model="form"
        :rules="rules"
        label-position="top"
        label-width="85px"
      >
        <el-form-item label="父节点" style="width:30%">
          <el-cascader
            v-model="form.parentId"
            style="width:100%"
            :disabled="!isEdit"
            :options="menuOption"
            :props="{ checkStrictly: true,label:'title',value:'id',disabled:'disabled',emitPath:false}"
            :show-all-levels="false"
            filterable
          />
        </el-form-item>
		<el-form-item label="所属系统" style="width:30%">
		  <el-select v-model="form.platform" placeholder="所属系统">
		    <el-option :value="1" label="管理系统" />
		  </el-select>
		</el-form-item>
		<el-form-item label="是否隐藏" style="width:30%">
		  <el-select v-model="form.hidden" placeholder="是否隐藏">
			<el-option
			  v-for="item in isnotOptions"
			  :key="item.value"
			  :label="`${item.label}`"
			  :value="item.value"
			/>
		  </el-select>
		</el-form-item>
		
		<el-form-item label="名称" prop="name" style="width:30%">
          <el-input
            v-model="form.name"
            autocomplete="off"
            placeholder="显示名称"
          />
        </el-form-item>
        <el-form-item label="路由" prop="path" style="width:40%">
          <el-input
            v-model="form.path"
            autocomplete="off"
            placeholder="唯一英文字符串"
          />
        </el-form-item>
		<el-form-item label="排序" prop="sort" style="width:18%">
		  <el-input v-model.number="form.sort" autocomplete="off" />
		</el-form-item>
        
        <el-form-item label="图标" prop="icon" style="width:30%">
          <icon :meta="form" style="width:100%" />
        </el-form-item>
        <el-form-item label="组件地址" prop="component" style="width:61%">
          <el-input v-model="form.component" autocomplete="off" />
        </el-form-item>
		
        <el-form-item label="KeepAlive" prop="keepAlive" style="width:30%">
          <el-select v-model="form.keepAlive" style="width:100%" placeholder="是否keepAlive缓存页面">
			<el-option
			  v-for="item in isnotOptions"
			  :key="item.value"
			  :label="`${item.label}`"
			  :value="item.value"
			/>
          </el-select>
        </el-form-item>
		<el-form-item label="类型" prop="type" style="width:30%">
		  <el-select v-model="form.type" style="width:100%">
			<el-option
			  v-for="item in typeOptions"
			  :key="item.value"
			  :label="`${item.label}`"
			  :value="item.value"
			/>
		  </el-select>
		</el-form-item>
		
		<el-form-item label="备注" prop="remark" style="width:61%">
		  <el-input v-model="form.remark" autocomplete="off" />
		</el-form-item>
      </el-form>
	  
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="closeDialog">取 消</el-button>
          <el-button size="small" type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
	
	<el-drawer v-if="drawer" v-model="drawer" :with-header="false" size="40%" title="菜单配置">
	  <el-tabs :before-leave="autoEnter" class="menu-box" type="border-card">
	    <el-tab-pane label="关联资源">
	      <Resource ref="menus" :row="activeRow" @changeRow="changeRow" />
	    </el-tab-pane>
	  </el-tabs>
	</el-drawer>
  </div>
</template>

<script setup>
import {
  getMenuList,
  saveMenu,
  deleteMenu
} from '@/api/menu'
import { getDict } from '@/utils/dictionary'
import icon from '@/view/superAdmin/menu/icon.vue'
import Resource from '@/view/superAdmin/menu/components/resources.vue'
import warningBar from '@/components/warningBar/warningBar.vue'
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const rules = reactive({
  name: [
    { required: true, message: '请输入菜单显示名称', trigger: 'blur' }
  ],
  path: [{ required: true, message: '请输入菜单路由', trigger: 'blur' }]
})

const tableData = ref([])
const searchInfo = ref({})
// 查询
const getTableData = async() => {
  const table = await getMenuList({ platform: 1, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data
  }
}

const initPage = async() => {
	{
	  var op = await getDict("menu_type")
	  if(op){
		typeOptions.value = op
	  }
	}
	{
	  var op = await getDict("isnot")
	  if(op){
		isnotOptions.value = op
	  }
	}
	getTableData()
}

initPage()

const form = ref({
  id: 0,
  platform: 1,
  path: '',
  name: '',
  hidden: -1,
  parentId: '',
  component: '',
  keepAlive: -1,
  sort: 0,
  type: 'menu'
})

const handleClose = (done) => {
  initForm()
  done()
}
// 删除菜单
const deleteMenuAction = (id) => {
  ElMessageBox.confirm('此操作将永久删除所有角色下该菜单, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async() => {
      const res = await deleteMenu({ "id": id })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功!'
        })
        getTableData()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}
// 初始化弹窗内表格方法
const menuForm = ref(null)
const initForm = () => {
  menuForm.value.resetFields()
  form.value = {
    id: 0,
	platform: 1,
    path: '',
    name: '',
    hidden: -1,
    parentId: '',
    component: '',
	keepAlive: -1,
	sort: 0,
	type: 'menu'
  }
}
// 关闭弹窗
const dialogFormVisible = ref(false)
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}
// 添加menu
const enterDialog = async() => {
  menuForm.value.validate(async valid => {
    if (valid) {
      const res = await saveMenu(form.value)
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '保存成功'
        })
        getTableData()
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}

const isnotOptions = ref([])
const typeOptions = ref([])

const menuOption = ref([
  {
    id: 0,
    title: '根菜单'
  }
])
const setOptions = (isEdit) => {
  menuOption.value = [
    {
      id: 0,
      title: '根菜单'
    }
  ]
  if(isEdit){
	  setMenuOptions(tableData.value, menuOption.value, false)
  }
}
const setMenuOptions = (menuData, optionsData, disabled) => {
  menuData &&
        menuData.forEach(item => {
          if (item.children && item.children.length) {
            const option = {
              title: item.name,
              id: item.id,
              disabled: disabled || item.id === form.value.id,
              children: []
            }
            setMenuOptions(
              item.children,
              option.children,
              disabled || item.id === form.value.id
            )
            optionsData.push(option)
          } else {
            const option = {
              title: item.name,
              id: item.id,
              disabled: disabled || item.id === form.value.id
            }
            optionsData.push(option)
          }
        })
}

// 添加菜单方法，id为 0则为添加根菜单
const isEdit = ref(false)
const dialogTitle = ref('新增菜单')
const addMenu = (row) => {
	if(row){
		dialogTitle.value = '添加子菜单'
		form.value.parentId = row.id
		isEdit.value = false
		setOptions(true)
		dialogFormVisible.value = true
	}else{
		dialogTitle.value = '新增根菜单'
		form.value.parentId = 0
		isEdit.value = false
		setOptions(false)
		dialogFormVisible.value = true
	}
}
// 修改菜单方法
const editMenu = async(row) => {
  dialogTitle.value = '编辑菜单'
  form.value = row
  isEdit.value = true
  setOptions(true)
  dialogFormVisible.value = true
}

const drawer = ref(false)
const activeRow = ref({})
const resources = ref(null)

const changeRow = (key, value) => {
  activeRow.value[key] = value
}
const autoEnter = (activeName, oldActiveName) => {
  const paneArr = [resources]
  if (oldActiveName) {
    if (paneArr[oldActiveName].value.needConfirm) {
      paneArr[oldActiveName].value.enterAndNext()
      paneArr[oldActiveName].value.needConfirm = false
    }
  }
}
const opdendrawer = (row) => {
  drawer.value = true
  activeRow.value = row
}
</script>

<script>
export default {
  name: 'Menus',
}
</script>

<style scoped lang="scss">
.warning {
  color: #dc143c;
}
.icon-column{
  display: flex;
  align-items: center;
  .el-icon{
    margin-right: 8px;
  }
}
.menu-box {
  .el-tabs__content {
    height: calc(100vh - 72px);
    overflow: auto;
  }
}
</style>
